package com.lt.flashcard.view;

import java.util.ArrayList;
import java.util.List;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.Notification;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.NotificationService;
import com.lt.flashcard.model.service.Repository;
import com.lt.flashcard.model.service.UserService;

public class V_notificationVm {
	private List<Notification> notifications;
	
	@Init
	public void Init(){
		if(Utility.isLogin()){
    		User user = Utility.getUser();
    		NotificationService srv = Repository.getInstance().getNotificationService();
    		notifications = srv.getQuickNotificationOfUser(user);
    		srv.updateUnread(user);
		}else{
			Utility.redirect("/login.zul", false);
		}
	}
	
	public List<Notification> getNotifications(){
		if(notifications == null)
			notifications = new ArrayList<Notification>();
		return notifications;
	}
	
	@Command
	@NotifyChange("notifications")
	public void doAcceptFriendRequest(@BindingParam("notify") Notification notify){
		UserService srv = Repository.getInstance().getUserService();
		NotificationService nsrv = Repository.getInstance().getNotificationService();
		
		srv.addFriendShip(notify.getSourceuid(), notify.getTargetuid());
		nsrv.saveNotification(notify);
		
		Notification friendship1 = new Notification();
		friendship1.setSourceuid(notify.getSourceuid());
		friendship1.setSourceuname(notify.getSourceuname());
		friendship1.setTargetuid(notify.getTargetuid());
		friendship1.setType(Notification.TYPE_ACCEPTEDFRIENDREQUEST);
		nsrv.saveNotification(friendship1);
		
		Notification friendship2 = new Notification();
		friendship2.setSourceuid(notify.getTargetuid());
		friendship2.setSourceuname(srv.findByID(notify.getTargetuid()).getUsername());
		friendship2.setTargetuid(notify.getSourceuid());
		friendship2.setType(Notification.TYPE_ACCEPTEDFRIENDREQUEST);
		nsrv.saveNotification(friendship2);
		notifications = nsrv.getQuickNotificationOfUser(Utility.getUser());
	}
}
